<?php

namespace App\Http\Controllers\Api\Home;

use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Api\VerificationCodeRequest;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Overtrue\EasySms\EasySms;


class VerificationCodesController extends Controller
{
    //
    public function store(VerificationCodeRequest $request,EasySms $easySms){
        $captchaData = Cache::get($request->captcha_key);

        if (!$captchaData){
            return $this->response->error('图形验证码失效',422);
        }

 /*       if (!hash_equals($captchaData['code'],$request->captcha_code)){
            Cache::forget($request->captcha_key);
            return $this->response->errorUnauthorized('验证码错误');
        }*/
        $phone = $captchaData['phone'];
        $code = str_pad(random_int(1,9999),4,0,STR_PAD_LEFT);
        if (true){
            $code = '1234';
        }else{
            try{
                $result = $easySms->send($phone,[
                    'content' => "您的验证码为{$code}"
                ]);
            }catch (ClientException $exception){
                $response = $exception->getResponse();
                $result = \GuzzleHttp\json_decode($response->getBody()->getContents(),true);
                return $this->response->errorInternal($result['msg'] ?? '短信发送异常');
            }
        }



        $key = 'verification' . str_random(15);
        $expiredAt = now()->addMinute(1000);

        Cache::put($key,['phone'=>$phone,'code'=>$code],$expiredAt);

        return $this->response->array([
            'key'=> $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ])->setStatusCode(201);
    }

    public function index(){
        return 111;
    }
}
